package com.store.app.widget;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.store.app.R;
import com.store.app.adapter.GridViewGuiGeAdapter;
import com.store.app.bean.SpecificationsBean;
import com.store.app.bean.WypGoodsBean;
import com.store.app.imlife.utils.ToastTools;
import com.store.app.net.NetRequest;
import com.store.app.net.ifc.IOnHttpListener;
import com.store.app.utils.GoToLogin;
import com.store.app.utils.MoneyUtil;
import com.store.app.utils.ToastUtils;
import com.store.app.utils.Utils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/3/12.
 */
public class BookedOnlinePopupWindow implements IOnHttpListener {
    private PopupWindow popupwindow;
    private View dataSelectView;
    private Context Context;
    private ImageView img;
    private TextView tv_price, tv_qiding, tv_xiangou, tv_kucun, tv_count_reduce, tv_count_add, tv_buy_count,
            tv_sum, tv_add;
    private Button bt_submit;
    //    private BookedBean bean;
    private WypGoodsBean bean;
    private LinearLayout lin_top;
    private String goods_id;
    //加载数据LinearLayout
    private LinearLayout lin, lin_dismiss;
    private ProgressBar progress;
    private TextView loading_tv;
    private static final int MSG_LOAD_SUCCESS = 11;      //加载更多
    private static final int MSG_REFRESH_FAILED = 12;
    private GridView gridView;
    private NetRequest netRequest;
    private LinearLayout ll_xiangou;
    private int allStock = 0;
    private String priceArea = "0";
    public BookedOnlinePopupWindow(String goods_id) {
        this.goods_id = goods_id;


    }

    private GoToLogin goToLogin;

    public PopupWindow getPopupWindow(Context context) {
        goToLogin = new GoToLogin(context);
        this.Context = context;
        popupwindow = new PopupWindow(context);
        LayoutInflater mLayoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
        dataSelectView = mLayoutInflater.inflate(
                R.layout.goods_order_dialog, null);
        // 日期选择器的控件
        img = (ImageView) dataSelectView
                .findViewById(R.id.iv);
        tv_price = (TextView) dataSelectView
                .findViewById(R.id.tv_price);
        gridView = (GridView) dataSelectView.findViewById(R.id.gv_guige);//规格
        tv_qiding = (TextView) dataSelectView.findViewById(R.id.tv_qiding);//起订
        tv_xiangou = (TextView) dataSelectView.findViewById(R.id.tv_xiangou);//限购
        ll_xiangou = (LinearLayout) dataSelectView.findViewById(R.id.ll_xiangou);//限购
        tv_kucun = (TextView) dataSelectView.findViewById(R.id.tv_kucun);//库存
        tv_count_reduce = (TextView) dataSelectView.findViewById(R.id.tv_reduce);
        tv_count_add = (TextView) dataSelectView.findViewById(R.id.tv_add);
        tv_buy_count = (TextView) dataSelectView.findViewById(R.id.tv_buy_count);
        tv_sum = (TextView) dataSelectView.findViewById(R.id.tv_sum);
        bt_submit = (Button) dataSelectView.findViewById(R.id.bt_submit);
        tv_add = (TextView) dataSelectView.findViewById(R.id.tv_address);
        lin_top = (LinearLayout) dataSelectView.findViewById(R.id.lin_top_null);
        lin = (LinearLayout) dataSelectView.findViewById(R.id.loading);
        progress = (ProgressBar) dataSelectView.findViewById(R.id.loading_progress);
        loading_tv = (TextView) dataSelectView.findViewById(R.id.loading_tv);
        lin.setVisibility(View.VISIBLE);
        lin_dismiss = (LinearLayout) dataSelectView.findViewById(R.id.lin_dismiss);
        popupwindow.setWidth(LayoutParams.MATCH_PARENT);
        popupwindow.setHeight(LayoutParams.WRAP_CONTENT);
        popupwindow.setBackgroundDrawable(new BitmapDrawable());
        popupwindow.setFocusable(true);
        popupwindow.setOutsideTouchable(true);
        popupwindow.setContentView(dataSelectView);
        popupwindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                if (disMissListener != null) {
                    disMissListener.dissmiss();
                }
            }
        });
        lin_top.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupwindow.dismiss();
            }
        });

        netRequest = new NetRequest(this, context);
        netRequest.requestQueryGoodsInfo(1, goods_id);
//        new QuertyGoodsInfo().start();

        return popupwindow;
    }

    public DisMissListener disMissListener;

    @Override
    public void onAfinalFail() {

    }

    @Override
    public void onExecuteSuccess(int requestId, String result, String msg) {
        if (requestId == 1) {
            Gson gson = new Gson();
            Type type = new TypeToken<WypGoodsBean>() {
            }.getType();
//            Message msg = Message.obtain();
//            msg.what = MSG_LOAD_SUCCESS;
            try {
                JSONObject obj1 = new JSONObject(result);
                JSONArray standard_list = obj1.getJSONArray("standard_list");//规格list
                List<SpecificationsBean> specificationsBeanList = new ArrayList<>();
                List<Double> doubleListPrice = new ArrayList<>();
                allStock = 0;
                DecimalFormat df   = new DecimalFormat("######0.00");
                for (int i = 0; i < standard_list.length(); i++) {
                    JSONObject spObk = standard_list.getJSONObject(i);
                    SpecificationsBean specificationsBean = new SpecificationsBean();
                    specificationsBean.setDesc1(spObk.optString("desc1"));
                    specificationsBean.setGoods_stock_id(spObk.optString("goods_stock_id"));
                    specificationsBean.setSale_qty(spObk.optString("sale_qty"));
                    specificationsBean.setSales_price(spObk.optString("sales_price"));
                    specificationsBean.setSku(spObk.optString("sku"));
                    specificationsBean.setStock_qty(spObk.optString("stock_qty"));
                    specificationsBeanList.add(specificationsBean);
                    doubleListPrice.add(Double.parseDouble(MoneyUtil.formatMoney(spObk.optString("sales_price"))));
                    allStock += Integer.parseInt(spObk.optString("sale_qty"));
                }

                if(!MoneyUtil.formatMoney(Collections.min(doubleListPrice)+"").equals(MoneyUtil.formatMoney(Collections.max(doubleListPrice)+""))){
                    priceArea = MoneyUtil.formatMoney(Collections.min(doubleListPrice)+"")+"-"+ MoneyUtil.formatMoney(Collections.max(doubleListPrice)+"");
                }else{
                    priceArea = "";
                }



                if(standard_list.length()<=1){
                    allStock = 0;
                    priceArea = "";
                }

                Log.v("zyl","allStock:"+allStock);
                Log.v("zyl","doubleListPrice max:"+ Collections.max(doubleListPrice));
                Log.v("zyl","doubleListPrice min :"+ Collections.min(doubleListPrice));
                JSONObject jsonObject =obj1.getJSONObject("detail");
                Log.v("zyl", "json list:" + jsonObject.toString());
                bean = gson.fromJson(jsonObject.toString(), type);
                if(TextUtils.isEmpty(bean.getWarehouse_id())|TextUtils.isEmpty(bean.getSupplier_id())){
                    ToastUtils.showTextToast(Context,"商品信息错误！");
                    popupwindow.dismiss();
                    return ;
                }


                JSONArray jsonArray = new JSONArray(bean.getPic_info());
                JSONObject picObj = jsonArray.getJSONObject(0);
                String s_id = picObj.getString("path_id");
                String docMap = obj1.getString("doc_url");
                Log.v("zyl", "docMap:" + docMap);
                Map<String, String> map = Utils.getMapForJson(docMap);
                String url = map.get(s_id);
                bean.setPic_show_url(url);
                bean.setSpecificationsBeanList(specificationsBeanList);
                lin.setVisibility(View.GONE);
                bean.setReal_qty(specificationsBeanList.get(0).getSale_qty());//设置库存，默认设置第一个规格的库存
                bean.setLastMoney(specificationsBeanList.get(0).getSales_price());//设置价格，默认设置第一个规格的库存
                bean.setSupidAndwarehouse(bean.getSupplier_id() + bean.getWarehouse_id());
                bean.setGoodsidAndstockId(bean.getGoods_id() + bean.getSpecificationsBeanList().get(0).getGoods_stock_id());



//                Log.v("zyl", "此时bean数据：" + bean.toString());
//                Log.v("zyl", "此时bean数据size：" + bean.getSpecificationsBeanList().size());
                setData();
                int qiding = Integer.parseInt(tv_qiding.getText().toString().trim());
                int kucun = Integer.parseInt(tv_kucun.getText().toString().trim());
                if(qiding>kucun){
                    tv_count_add.setEnabled(false);
                    tv_count_add.setBackgroundResource(R.drawable.wyp_add_gray);
                }else{
                    tv_count_add.setEnabled(true);
                    tv_count_add.setBackgroundResource(R.drawable.wyp_add_bg);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onExecuteFail(int requestId, String msg) {
        if (requestId == 1) {
            loadingfail();
        }
    }

    public interface DisMissListener {
        public void dissmiss();
    }

    public void setonDisMissListener(DisMissListener listener) {
        this.disMissListener = listener;
    }

    public PostListener postListener;

    public interface PostListener {
        public void post(WypGoodsBean bean, int num, String money);

    }

    public void setonPostListener(PostListener postListener) {
        this.postListener = postListener;
    }

    private void loadingfail() {
        if (lin.getVisibility() == View.VISIBLE) {
            progress.setVisibility(View.GONE);
            loading_tv.setText("请点击重新加载");
            lin.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    progress.setVisibility(View.VISIBLE);
                    loading_tv.setText("加载中...");
                    netRequest.requestQueryGoodsInfo(1, goods_id);
                }
            });
        }
    }


    private void setData() {
        final GridViewGuiGeAdapter adapter = new GridViewGuiGeAdapter(Context, bean.getSpecificationsBeanList());
        gridView.setAdapter(adapter);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                adapter.setSelection(position);
                adapter.notifyDataSetChanged();
                tv_kucun.setText(bean.getSpecificationsBeanList().get(position).getSale_qty());//库存
                tv_price.setText(bean.getSpecificationsBeanList().get(position).getSales_price());//设置商品单价，默认取第一个规格的价格
                //当前文本的数量
                int currentCount = Integer.parseInt(tv_buy_count.getText().toString().trim());
                int chooseStock = Integer.parseInt(tv_kucun.getText().toString().trim());
                Log.v("zyl","currentCount:"+currentCount);
                Log.v("zyl","chooseStock:"+chooseStock);
                if(currentCount>chooseStock){

                    int min = Integer.parseInt(bean.getMin_buy_qty());
                    //选中规格的库存小于最低起订量
                    if(chooseStock<min){
                        tv_count_add.setEnabled(false);
                        Log.v("zyl", "选中规格的库存小于最低起订量，不让它添加了");
                    }else{
                        //得到余数
                        int yushu = chooseStock%min;
                        if(yushu==0){
                            Log.v("zyl","余数为0，则直接显示所剩库存");
                            tv_buy_count.setText(chooseStock+"");
                            tv_sum.setText(MoneyUtil.moneyMul(tv_buy_count.getText().toString().trim()+"",tv_price.getText().toString().trim()));
                        }else if(yushu>0){
                            Log.v("zyl","余数不为0，则直接显示所剩库存-余数");
                            tv_buy_count.setText((chooseStock-yushu)+"");
                            tv_sum.setText(MoneyUtil.moneyMul(tv_buy_count.getText().toString().trim()+"",tv_price.getText().toString().trim()));
                        }
                    }
                }else{
                    tv_count_add.setEnabled(true);
                }

                tv_sum.setText(MoneyUtil.moneyMul(bean.getSpecificationsBeanList().get(position).getSales_price(), tv_buy_count.getText().toString().trim()));
                bean.setChooseIndexSpeci(position);
                bean.setGoodsidAndstockId(bean.getGoods_id() + bean.getSpecificationsBeanList().get(position).getGoods_stock_id());
                bean.setLastMoney(bean.getSpecificationsBeanList().get(position).getSales_price());

                int qiding = Integer.parseInt(tv_qiding.getText().toString().trim());
                int kucun = Integer.parseInt(tv_kucun.getText().toString().trim());
                if(qiding>kucun){
                    tv_count_add.setEnabled(false);
                    tv_count_add.setBackgroundResource(R.drawable.wyp_add_gray);
                }else{
                    tv_count_add.setEnabled(true);
                    tv_count_add.setBackgroundResource(R.drawable.wyp_add_bg);
                }

            }
        });

//        String emsMoney = bean.getShipping_fee();
//        if (!TextUtils.isEmpty(emsMoney)) {
//            if (emsMoney.equals("0") | emsMoney.equals("0.00")) {
//                tvEmsInfo.setText("包邮");
////                tvEmsInfo.setTextColor(Color.parseColor("#F96116"));
//            } else {
//                tvEmsInfo.setText("邮费：" + emsMoney);
////                tvEmsInfo.setTextColor(Color.parseColor("#F96116"));
//            }
//        }
        String payment_way = bean.getPayment_way();
        if (payment_way.equals("online")) {
            bt_submit.setText("加入购物车");
        } else {
            bt_submit.setText("提交订单");
        }
        Log.v("zyl", "运费：" + bean.getShipping_fee());


        String s_sale_qty = bean.getSale_qty();
        int i_sale_qty = 0;
        try {
            i_sale_qty = Integer.parseInt(s_sale_qty);
            if (i_sale_qty < 0) {
                i_sale_qty = 0;
            }
        } catch (Exception e) {

        }
//
        if(TextUtils.isEmpty(priceArea)){
            adapter.setSelection(0);
            tv_kucun.setText(bean.getSpecificationsBeanList().get(0).getSale_qty());//库存
            tv_price.setText("" + bean.getSpecificationsBeanList().get(0).getSales_price());//设置商品单价，默认取第一个规格的价格
        }else{
            adapter.setSelection(99);
            tv_price.setText(priceArea);
            tv_kucun.setText(allStock+"");
        }

        tv_qiding.setText(bean.getMin_buy_qty());//起订
        String s_max_buy_qty = bean.getMax_buy_qty();
        if (!TextUtils.isEmpty(s_max_buy_qty) && !s_max_buy_qty.equals("0")) {
            ll_xiangou.setVisibility(View.VISIBLE);
            tv_xiangou.setText(bean.getMax_buy_qty());//限购
        }else{
            ll_xiangou.setVisibility(View.GONE);
        }
//      tv_qiding.setText("起订量" + bean.getMin_buy_qty()+bean.getGoods_unit());
        lin_dismiss.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupwindow.dismiss();
            }
        });
        //价格直接显示选中那件规格的商品的价格
        tv_sum.setText(MoneyUtil.moneyMul(bean.getSpecificationsBeanList().get(0).getSales_price(), bean.getMin_buy_qty()));
        tv_buy_count.setText(bean.getMin_buy_qty());


        tv_count_reduce.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int i_count = Integer.parseInt(tv_buy_count.getText().toString());
                String minbuy_qty = bean.getMin_buy_qty();
                int i_min_count = 1;
                if (TextUtils.isEmpty(minbuy_qty) || Integer.parseInt(minbuy_qty) < 1) {
                    i_min_count = 1;
                } else {
                    i_min_count = Integer.parseInt(minbuy_qty);
                }

                if (i_count > i_min_count) {
                    i_count = i_count - i_min_count;
                    if (i_count == i_min_count) {
                        tv_count_reduce.setBackgroundResource(R.drawable.wyp_min_bg_gray);
                    }
                    tv_buy_count.setText(i_count + "");
                    tv_sum.setText(MoneyUtil.moneyMul(tv_price.getText().toString().trim(), tv_buy_count.getText().toString().trim()));
                }
            }
        });


        final int maxNum;//限购数量
        if (TextUtils.isEmpty(bean.getMax_buy_qty())) {
            maxNum = 0;
        } else {
            maxNum = Integer.parseInt((bean.getMax_buy_qty()));
        }
        tv_count_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(adapter.getSelection()==99){
                    ToastTools.showShort(Context,"请选择规格！");
                    return;
                }
//                tv_count_reduce.setBackgroundResource(R.drawable.wyp_min_bg);
                //不限制
                if (maxNum <= 0) {
                    int i_count = Integer.parseInt(tv_buy_count.getText().toString());
                    int i_min_count = Integer.parseInt(bean.getMin_buy_qty());
                    i_count = i_count + i_min_count;
                    //如果超过库存就不添加了
                    if (i_count > Integer.parseInt(tv_kucun.getText().toString().trim())) {
                        ToastTools.showShort(Context, "库存不足！");
                    } else {
                        tv_buy_count.setText(i_count + "");//设置添加后的数量，则刷新总价
                        tv_sum.setText(MoneyUtil.moneyMul(tv_price.getText().toString().trim(), tv_buy_count.getText().toString().trim()));
                    }
                } else {
                    int i_count = Integer.parseInt(tv_buy_count.getText().toString());
                    int i_min_count = Integer.parseInt(bean.getMin_buy_qty());
                    i_count = i_count + i_min_count;
                    //如果购买数量大于了限购，则不允许加了
                    if (i_count > maxNum) {
                        ToastTools.showShort(Context, "超过限购！");
                    } else if (i_count > Integer.parseInt(tv_kucun.getText().toString().trim())) {
                        ToastTools.showShort(Context, "库存不足！");
                    } else {
                        tv_buy_count.setText(i_count + "");
                        tv_sum.setText(MoneyUtil.moneyMul(tv_price.getText().toString().trim(), tv_buy_count.getText().toString().trim()));
                    }
                }
            }
        });
        bt_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(adapter.getSelection()==99){
                    ToastTools.showShort(Context,"请选择规格！");
                    return;
                }
                int qidong = Integer.parseInt(tv_qiding.getText().toString().trim());
                int kucun = Integer.parseInt(tv_kucun.getText().toString().trim());
                if(qidong>kucun){
                    ToastTools.showShort(Context,"起订量大于库存，无法加入购物车！");
                    return;
                }
                if (postListener != null) {
                    postListener.post(bean, Integer.parseInt(tv_buy_count.getText().toString()), MoneyUtil.formatMoney(tv_sum.getText().toString()));
                }
            }
        });
        ImageLoader.getInstance().displayImage(bean.getPic_show_url(), img);
    }
}
